package com.psp.bu.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.northend.util.AppTextUtil;
import com.northend.util.NumUtil;
import com.psp.bu.cache.dao.UserCacheDao;
import com.psp.bu.controller.res.BaseResult;
import com.psp.bu.controller.res.ObjectResult;
import com.psp.bu.controller.res.bean.RUserBean;
import com.psp.bu.controller.res.enumModel.ServiceCategoryEnum;
import com.psp.bu.controller.springmvc.req.CheckLoginUserParam;
import com.psp.bu.controller.springmvc.req.CheckRegUserParam;
import com.psp.bu.controller.springmvc.req.ConfirmFindPwdCodeParam;
import com.psp.bu.controller.springmvc.req.GetUserParam;
import com.psp.bu.controller.springmvc.req.LoginParam;
import com.psp.bu.controller.springmvc.req.ResetPasswordParam;
import com.psp.bu.controller.springmvc.req.ResetPwdParam;
import com.psp.bu.controller.springmvc.req.SendFindPwdCodeParam;
import com.psp.bu.controller.springmvc.req.UpdatePhoneParam;
import com.psp.bu.controller.springmvc.req.UpdateUserParam;
import com.psp.bu.model.Code;
import com.psp.bu.model.UserBean;
import com.psp.bu.service.UserService;
import com.psp.bu.service.exception.ServiceException;

@Component
public class UserController {
	Logger logger = Logger.getLogger(UserController.class);
	@Autowired
	UserService userServiceImpl;
	@Autowired
	UserCacheDao userCacheImpl;

	/**
	 * 登录
	 * 
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 */
	public ObjectResult<RUserBean> login(LoginParam param, HttpServletRequest request, HttpServletResponse response) {
		ObjectResult<RUserBean> result = new ObjectResult<RUserBean>();

		try {
			String userName = param.getUserName();
			String pwd = param.getPassword();
			String vcode = param.getImgCode();
			String device = param.getDevice();
			String sessionId = request.getSession().getId();
			String ip = AppTextUtil.getIpAddr(request);
			UserBean user = userServiceImpl.login(sessionId, userName, pwd, vcode, device, ip);
			logger.info("login user is:" + user);
			if (user != null) {
				RUserBean data = new RUserBean();
				data.setAccountMark(user.getBuid());
				data.setUserName(user.getNickName());
				data.setEmail(user.getEmail());
				data.setGender(user.getGender());
				data.setHeadIcon(user.getHeadIcon());
				data.setIdno(user.getIdNo());
				data.setPhone(user.getPhone());
				data.setState(user.getState());
				result.setToken(sessionId);
				result.setData(data);
				result.setFlag(true);
			} else {
				Code code = userCacheImpl.getLoginCode(userName);
				if (code != null) {
					result.setErrorCount(code.getNum());
				}
			}

		} catch (ServiceException e) {
			result.setFlag(false);
			result.setRescode(e.getServiceCode());
			result.setMsg(e.getServiceMsg());
		}
		return result;
	}

	/**
	 * 检查登录用户
	 * 
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 */
	public BaseResult checkRegUser(CheckRegUserParam param, HttpServletRequest request, HttpServletResponse response) {
		String username = param.getUserName();
		BaseResult result = new BaseResult();
		try {
			UserBean user = userServiceImpl.existUser(1, username);
			if (user != null) {
				result.setFlag(true);
			}
		} catch (ServiceException e) {
			result.setFlag(false);
			result.setMsg(e.getServiceMsg());
		}
		return result;
	}

	/**
	 * 检查登录用户
	 * 
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 */
	public BaseResult checkLoginUser(CheckLoginUserParam param, HttpServletRequest request,
			HttpServletResponse response) {
		String username = param.getUserName();
		BaseResult result = new BaseResult();
		try {
			UserBean user = userServiceImpl.existUser(2, username);
			if (user != null) {
				result.setFlag(true);
			}
		} catch (ServiceException e) {
			result.setFlag(false);
			result.setMsg(e.getServiceMsg());
		}
		return result;
	}

	/**
	 * 发送找回密码验证码
	 * 
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 */
	public ObjectResult<RUserBean> sendFindPwdCode(SendFindPwdCodeParam param, HttpServletRequest request,
			HttpServletResponse response) {
		ObjectResult<RUserBean> result = new ObjectResult<RUserBean>();

		String userName = param.getAccount();
		String code = param.getImgCode();
		String key = param.getImgKey();
		try {
			UserBean user = userServiceImpl.sendFindPwdCode(userName, code, key);

			if (user != null) {
				RUserBean data = new RUserBean();
				data.setUserName(user.getNickName());
				data.setEmail(user.getEmail());
				data.setPhone(user.getPhone());
				result.setData(data);
				result.setFlag(true);
			}
		} catch (ServiceException e) {
			result.setFlag(false);
			result.setMsg(e.getServiceMsg());
		}
		return result;
	}

	/**
	 * 确认找回密码发送验证码
	 * 
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 */
	public ObjectResult<RUserBean> confirmFindPwdCode(ConfirmFindPwdCodeParam param, HttpServletRequest request,
			HttpServletResponse response) {
		ObjectResult<RUserBean> result = new ObjectResult<RUserBean>();
		String account = param.getAccount();
		String vcode = param.getVcode();
		try {
			UserBean user = userServiceImpl.confirmFindPwdCode(account, vcode);
			if (user != null) {
				RUserBean data = new RUserBean();
				data.setUserName(user.getNickName());
				data.setEmail(user.getEmail());
				data.setPhone(user.getPhone());
				result.setData(data);
				result.setFlag(true);
			}
		} catch (ServiceException e) {
			result.setFlag(false);
			result.setMsg(e.getServiceMsg());
		}
		return result;
	}

	/**
	 * 找回密码，重置密码
	 * 
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 */
	public BaseResult resetPwd(ResetPwdParam param, HttpServletRequest request, HttpServletResponse response) {
		String phone = param.getAccount();
		String pwd = param.getPwd();
		String confirmPwd = param.getConfirmPwd();
		String vcode = param.getVcode();
		BaseResult result = new BaseResult();
		try {
			boolean flag = userServiceImpl.resetPwd(phone, vcode, pwd, confirmPwd);
			if (flag) {
				result.setFlag(true);
			}
		} catch (ServiceException e) {
			result.setFlag(false);
			result.setMsg(e.getServiceMsg());
		}
		return result;
	}

	/**
	 * 获取用户信息
	 * 
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 */
	public ObjectResult<RUserBean> getUser(GetUserParam param, HttpServletRequest request,
			HttpServletResponse response) {
		ObjectResult<RUserBean> result = new ObjectResult<RUserBean>();
		String token = (String) request.getAttribute("token");
		String UserId = (String) request.getAttribute("userId");
		try {
			UserBean user = userServiceImpl.getUser(UserId);
			logger.info("login user is:" + user);
			if (user != null) {
				RUserBean data = new RUserBean();
				data.setUserName(user.getNickName());
				data.setEmail(user.getEmail());
				data.setGender(user.getGender());
				data.setHeadIcon(user.getHeadIcon());
				data.setIdno(user.getIdNo());
				data.setPhone(user.getPhone());
				data.setState(user.getState());
				data.setCateCode(user.getCateCode());
				data.setCateName(ServiceCategoryEnum.getName(user.getCateCode()));
				result.setData(data);
				result.setFlag(true);
			}
		} catch (ServiceException e) {
			result.setFlag(false);
			result.setMsg(e.getServiceMsg());
		}
		result.setToken(token);
		return result;
	}

	/**
	 * 更新用户信息
	 * 
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 */
	public ObjectResult<RUserBean> updateUser(UpdateUserParam param, HttpServletRequest request,
			HttpServletResponse response) {
		ObjectResult<RUserBean> result = new ObjectResult<RUserBean>();
		String token = (String) request.getAttribute("token");
		try {
			String content = param.getContent();
			String userId = (String) request.getAttribute("userId");
			int type = NumUtil.toInt(param.getType(), 1);
			UserBean user = userServiceImpl.updateUser(userId, content, type);

			if (user != null) {
				RUserBean data = new RUserBean();
				data.setUserName(user.getNickName());
				data.setEmail(user.getEmail());
				data.setGender(user.getGender());
				data.setHeadIcon(user.getHeadIcon());
				data.setIdno(user.getIdNo());
				data.setPhone(user.getPhone());
				data.setState(user.getState());
				result.setData(data);
				result.setFlag(true);
			}

		} catch (ServiceException e) {
			result.setFlag(false);
			result.setMsg(e.getServiceMsg());
		}
		result.setToken(token);
		return result;
	}

	/**
	 * 更新手机号，检验用户原手机号是否正确
	 * 
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 */
	public BaseResult updatePhone(UpdatePhoneParam param, HttpServletRequest request, HttpServletResponse response) {
		BaseResult result = new BaseResult();
		String token = (String) request.getAttribute("token");
		try {
			String phone = param.getPhone();
			String vcode = param.getVcode();
			boolean flag = userServiceImpl.checkUserPhone(phone, vcode);
			if (flag) {
				result.setFlag(true);
			}
		} catch (ServiceException e) {
			result.setFlag(false);
			result.setMsg(e.getServiceMsg());
		}
		result.setToken(token);
		return result;
	}

	public BaseResult resetPassword(ResetPasswordParam param, HttpServletRequest request,
			HttpServletResponse response) {
		BaseResult result = new BaseResult();
		String token = (String) request.getAttribute("token");
		String UserId = (String) request.getAttribute("userId");
		try {
			String oldPwd = param.getOldPwd();
			String password = param.getPassword();
			String confirmPwd = param.getConfirmPwd();
			boolean flag = userServiceImpl.resetPassword(UserId, oldPwd, password, confirmPwd);
			if (flag) {
				result.setFlag(true);
			}
		} catch (ServiceException e) {
			result.setFlag(false);
			result.setMsg(e.getServiceMsg());
		}
		result.setToken(token);
		return result;
	}

}
